package com.vip.jwt.common.utils.app;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.vip.jwt.common.utils.xcx.wx.WXUserInfo;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;

/**
 * App授权工具类（微信授权）
 */
public class APPWXAuthUtil {

    @Getter
    private static String APP_ID;

    @Getter
    private static String APP_SECRET;

    @Value("${app-wx-appid}")
    public void setAppId(String appId) {
        APP_ID = appId;
    }

    @Value("${app-wx-appsecret}")
    public void setAppSecret(String appSecret) {
        APP_SECRET = appSecret;
    }

    /**
     * 获取用户信息
     * @param accessToken 令牌
     * @param openid 用户唯一标识
     * @return
     */
    public static WXUserInfo getWXUserInfo(String accessToken, String openid){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid;
        String result = HttpRequest.get(url).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        WXUserInfo wxUserInfo = new WXUserInfo();
        wxUserInfo.setOpenid(jsonObject.get("openid").toString());
        wxUserInfo.setNickName(jsonObject.get("nickname").toString());
        wxUserInfo.setLanguage(jsonObject.get("language").toString());
        wxUserInfo.setGender(Integer.parseInt(jsonObject.get("sex").toString()));
        wxUserInfo.setCity(jsonObject.get("city").toString());
        wxUserInfo.setProvince(jsonObject.get("province").toString());
        wxUserInfo.setCountry(jsonObject.get("country").toString());
        wxUserInfo.setAvatarUrl(jsonObject.get("headimgurl").toString());
        wxUserInfo.setUnionid(jsonObject.get("unionid").toString());
        return wxUserInfo;
    }

}
